using Microsoft.AspNetCore.Mvc;
using Lzfy_His_Service.Models;
using Lzfy_His_Service.Services;

namespace Lzfy_His_Service.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class RefundTaskDetailController : ControllerBase
    {
        private readonly IRefundTaskDetailService _service;
        private readonly ILogger<RefundTaskDetailController> _logger;

        public RefundTaskDetailController(
            IRefundTaskDetailService service,
            ILogger<RefundTaskDetailController> logger)
        {
            _service = service;
            _logger = logger;
        }

        /// <summary>
        /// 获取所有退费任务详情记录
        /// </summary>
        [HttpPost("get-all")]
        public async Task<ActionResult<IEnumerable<RefundTaskDetailResponse>>> GetAll()
        {
            try
            {
                var result = await _service.GetAllAsync();
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting all refund task details");
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 根据ID获取退费任务详情记录
        /// </summary>
        [HttpPost("get-by-id")]
        public async Task<ActionResult<RefundTaskDetailResponse>> GetById([FromBody] IdRequest request)
        {
            try
            {
                var result = await _service.GetByIdAsync(request.Id);
                if (result == null)
                {
                    return NotFound($"RefundTaskDetail with id {request.Id} not found");
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting refund task detail by id: {Id}", request.Id);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 根据主表ID获取退费任务详情记录
        /// </summary>
        [HttpPost("get-by-master-id")]
        public async Task<ActionResult<IEnumerable<RefundTaskDetailResponse>>> GetByMasterId([FromBody] IdRequest request)
        {
            try
            {
                var result = await _service.GetByMasterIdAsync(request.Id);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting refund task details by master id: {MasterId}", request.Id);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 根据患者ID获取退费任务详情记录
        /// </summary>
        [HttpPost("get-by-patient-id")]
        public async Task<ActionResult<IEnumerable<RefundTaskDetailResponse>>> GetByPatientId([FromBody] PatientIdRequest request)
        {
            try
            {
                var result = await _service.GetByPatientIdAsync(request.PatientId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting refund task details by patient id: {PatientId}", request.PatientId);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 根据条件查询退费任务详情记录（分页）
        /// </summary>
        [HttpPost("get-with-filter")]
        public async Task<ActionResult<object>> GetWithFilter([FromBody] RefundTaskDetailQueryRequest request)
        {
            try
            {
                var (data, totalCount) = await _service.GetWithFilterAsync(request);
                return Ok(new
                {
                    data,
                    totalCount,
                    pageIndex = request.PageIndex,
                    pageSize = request.PageSize,
                    totalPages = (int)Math.Ceiling((double)totalCount / request.PageSize)
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting refund task details with filter");
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 创建退费任务详情记录
        /// </summary>
        [HttpPost("create")]
        public async Task<ActionResult<object>> Create([FromBody] RefundTaskDetailCreateRequest request)
        {
            try
            {
                var id = await _service.CreateAsync(request);
                return Ok(new { id });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error creating refund task detail");
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 批量创建退费任务详情记录
        /// </summary>
        [HttpPost("batch-create")]
        public async Task<ActionResult> BatchCreate([FromBody] BatchCreateTaskDetailRequest request)
        {
            try
            {
                var success = await _service.BatchCreateAsync(request);
                if (!success)
                {
                    return BadRequest("Failed to create batch refund task details");
                }
                return Ok(new { message = "批量创建成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error batch creating refund task details");
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 更新退费任务详情记录
        /// </summary>
        [HttpPost("update")]
        public async Task<ActionResult> Update([FromBody] RefundTaskDetailUpdateRequest request)
        {
            try
            {
                var success = await _service.UpdateAsync(request.Id, request);
                if (!success)
                {
                    return NotFound($"RefundTaskDetail with id {request.Id} not found");
                }
                return Ok(new { message = "更新成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating refund task detail: {Id}", request.Id);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 更新联系时间
        /// </summary>
        [HttpPost("update-contact-time")]
        public async Task<ActionResult> UpdateContactTime([FromBody] ContactUpdateRequest request)
        {
            try
            {
                var success = await _service.UpdateContactTimeAsync(request);
                if (!success)
                {
                    return BadRequest("Failed to update contact time. Maximum 5 contacts allowed or record not found.");
                }
                return Ok(new { message = "更新联系时间成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating contact time for refund task detail: {Id}", request.Id);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 删除退费任务详情记录
        /// </summary>
        [HttpPost("delete")]
        public async Task<ActionResult> Delete([FromBody] IdRequest request)
        {
            try
            {
                var success = await _service.DeleteAsync(request.Id);
                if (!success)
                {
                    return NotFound($"RefundTaskDetail with id {request.Id} not found");
                }
                return Ok(new { message = "删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error deleting refund task detail: {Id}", request.Id);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 根据主表ID删除所有相关的详情记录
        /// </summary>
        [HttpDelete("by-master/{masterId}")]
        public async Task<ActionResult> DeleteByMasterId(long masterId)
        {
            try
            {
                var success = await _service.DeleteByMasterIdAsync(masterId);
                if (!success)
                {
                    return NotFound($"No RefundTaskDetails found for master id {masterId}");
                }
                return NoContent();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error deleting refund task details by master id: {MasterId}", masterId);
                return StatusCode(500, "Internal server error");
            }
        }
    }
}